package com.example.financeapi.service.impl;

import com.example.financeapi.entity.FUser;
import com.example.financeapi.mapper.FUserMapper;
import com.example.financeapi.service.FUserService;
import com.example.financeapi.entity.vo.ResultException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户表(FUser)表服务实现类
 * @author Alvin
 * @since 2020-03-31 12:05:46
 */
@Slf4j
@Service
public class FUserServiceImpl implements FUserService {
    @Autowired
    private FUserMapper fUserMapper;

    /**
     * 查询用户详情
     * @param paramMap
     * @return
     */
    @Override
    public FUser getFUserByCode(Map<String, Object> paramMap) {
        return fUserMapper.getFUserByCode(paramMap);
    }

    /**
     * 查询用户列表
     * @param paramMap
     * @return
     */
    @Override
    public List<FUser> getFUserList(Map<String, Object> paramMap) {
        return fUserMapper.getFUserList(paramMap);
    }

    /**
     * 新增数据
     *
     * @param fUser 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
    public FUser insert(FUser fUser) {
        Map<String, Object> paramMap =new HashMap<>();
        try {
            paramMap.put("unionid",fUser.getUnionid());
            paramMap.put("mpOpenid",fUser.getMpOpenid());
            paramMap.put("miniappOpenid",fUser.getMiniappOpenid());
            FUser user =fUserMapper.getFUserByCode(paramMap);
            if(user==null){
                this.fUserMapper.insert(fUser);
            }else{
                throw new ResultException(-1, "该用户已存在！");
            }
        } catch (ResultException e) {
            e.printStackTrace();
        }
        return fUser;
    }

    /**
     * 修改数据
     *
     * @param fUser 实例对象
     * @return 实例对象
     */
    @Override
    public FUser update(FUser fUser) {
        Map<String,Object> map =new HashMap<>();
        map.put("id",fUser.getId());
        this.fUserMapper.update(fUser);
        return this.getFUserByCode(map);
    }

    /**
     * 通过主键删除数据
     *
     * @param userId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer userId) {
        return this.fUserMapper.deleteById(userId) > 0;
    }
}